from django.shortcuts import render
from django.shortcuts import HttpResponse
import json,time
from db.mydb import MyDBConnection
from db.dao.game_events import Game_events
from db.utils.dfutils import load_json_to_object
from db.utils.logutils import LogUtils
from db.dao.player import Player
from db.dao.team import Team
def game_events_index(request):
    current = 1#如果用户不提供，默认看第一页
    pagesize = 5#如果用户不提供，默认每页5条
    if request.method == 'GET':  #大小写
        myDBConnection = MyDBConnection()
        current = request.GET.get("current")
        pagesize = request.GET.get("pagesize")
        print(f'1111 {request.GET.get("current")}')
        offset = (int(current) - 1) * int(pagesize) #计算每页的第一条编号
        game_eventss_json = myDBConnection.fetch_data_by_sql(f"select * from game_events limit {offset},{pagesize}")
        msg = f'现在查看的是第{current}页，每页大小{pagesize}'
        print(game_eventss_json)
        code = 200
        rep_json =  {"code":code,"msg":msg,"game_eventss":game_eventss_json}
    if bool(request.GET.get('json'))==True:
        return HttpResponse(json.dumps(rep_json), content_type="application/json")
    else:
        return render(request, "game_events/index.html", rep_json)

# def game_events_add(request):
#     # p_id = request.POST.get("p_id")
#     # p_name = request.POST.get("p_name")
#     data = request.body.decode("utf-8") #获得提交的json格式的字符串参数
#     myDBConnection =MyDBConnection()  #连接数据库
#     game_events_json_obj = json.loads(data)  #j字符串转换为json
#     game_events = load_json_to_object(game_events_json_obj,Game_events()) #json对象转换为指定对象Game_events
#     myDBConnection.insert_entity(game_events) #新增一条gameevents，如果不需要存到mysql只使用大数据日志系统，注释本句
#     #----------关联查询开始-------------
#     session = myDBConnection.get_session()
#     player = session.query(Player).filter(Player.p_id==game_events.p_id).first()
#     team = session.query(Team).filter(Team.t_id == game_events.t_id).first()
#     session.flush()
#     session.close()
#     #----------关联查询结束-------------
#     game_events._player = player
#     game_events._team = team
#     #------------日志记录开始 ，使用自定义日志记录器LogUtils.log----------
#     path_name = 'd:/log/'
#     current_time = time.localtime(time.time())
#
#     current_time_str = time.strftime('%Y-%m-%d', current_time)  # 参数2为格式化字符串
#     print(current_time_str)
#     file_name = current_time_str + '_gamerecords.log'
#     LogUtils.log(path_name,file_name,game_events.format_str())
#
#     msg = f"{game_events.git_id}比赛事件添加成功"
#     code = 200
#     rep_json = {"code":code,"msg":msg}
#     return HttpResponse(json.dumps(rep_json,ensure_ascii=False), content_type="application/json")